package top.lingkang.finalsecurity.jakarta;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.lingkang.finalsecurity.common.base.FinalExceptionHandler;
import top.lingkang.finalsecurity.common.utils.StringUtils;

import java.io.IOException;

/**
 * @author lingkang
 * Created by 2022/1/7
 * @since 1.0.0
 */
public class DefaultFinalExceptionHandler implements FinalExceptionHandler<HttpServletRequest, HttpServletResponse> {
    private static final Logger log = LoggerFactory.getLogger(DefaultFinalExceptionHandler.class);

    @Override
    public void permissionException(Throwable e, HttpServletRequest request, HttpServletResponse response) {
        printError(e, request, response, 403);
    }

    @Override
    public void notLoginException(Throwable e, HttpServletRequest request, HttpServletResponse response) {
        printError(e, request, response, 400);
    }

    @Override
    public void exception(Throwable e, HttpServletRequest request, HttpServletResponse response) {
        e.printStackTrace();
        try {
            response.getWriter().println(e.getMessage());
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    private void printError(Throwable e, HttpServletRequest request, HttpServletResponse response, int code) {
        log.warn(e.getMessage() + "  url=" + request.getServletPath());
        String contentType = request.getContentType();
        if (StringUtils.isEmpty(contentType)) {
            contentType = "text/html; charset=UTF-8";
        }
        response.setContentType(contentType);
        response.setStatus(200);
        try {
            if (!contentType.toLowerCase().contains("html")) {
                response.getWriter().print("{\"code\":" + code + ",\"msg\":\"" + e.getMessage() + "\"}");
            } else {
                response.getWriter().print(e.getMessage());
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
}
